package com.xuelang.pipeline.worker.app.pv.impl;

import com.xuelang.pipeline.worker.app.common.util.K8sUtils;
import com.xuelang.pipeline.worker.app.common.util.VerifyUtil;
import com.xuelang.pipeline.worker.app.pv.VolumeService;
import com.xuelang.pipeline.worker.client.crd.dto.VolumeDTO;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

/**
 * @author liuyuan.ly
 * @since 2024/7/8 13:54
 */
@Service
@Slf4j
public class VolumeServiceImpl implements VolumeService {

    @Override
    public V1PersistentVolumeClaim createVolume(VolumeDTO volumeDTO) {
        K8sUtils.initApiClient(volumeDTO.getKubeConfig());
        V1PersistentVolumeClaim pvc = volumeDTO.getPvc();
        CoreV1Api api = new CoreV1Api();
        V1PersistentVolumeClaim claim = null;
        try {
            V1PersistentVolumeClaim volumeListByName = getVolumeListByName(volumeDTO);
            if (ObjectUtils.isEmpty(volumeDTO)) {
                claim = api.createNamespacedPersistentVolumeClaim(
                        volumeDTO.getNamespace(),
                        pvc,
                        null,
                        null,
                        null,
                        null
                );
            }
        } catch (ApiException e) {
            log.info("创建pvc失败:{},堆栈信息:", e.getResponseBody(), e);
            throw new RuntimeException(e.getResponseBody());
        }
        return claim;
    }

    @Override
    public V1PersistentVolumeClaim getVolumeListByName(VolumeDTO volumeDTO) {
        K8sUtils.initApiClient(volumeDTO.getKubeConfig());
        VerifyUtil.verifyStringNotBlank(volumeDTO.getPvcName(), "PVC名字为空");

        CoreV1Api api = new CoreV1Api();
        V1PersistentVolumeClaim v1PersistentVolumeClaim;
        try {
            v1PersistentVolumeClaim = api.readNamespacedPersistentVolumeClaim(volumeDTO.getPvcName(), volumeDTO.getNamespace(), null);
        } catch (ApiException e) {
            log.info("查询pvc失败:{},堆栈信息:", e.getResponseBody(), e);
            throw new RuntimeException(e.getResponseBody());
        }
        return v1PersistentVolumeClaim;
    }


}
